package com.evaluation.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.evaluation.dto.PJDTO;
import com.evaluation.entity.*;
import com.evaluation.enums.UserTypeEnum;
import com.evaluation.mapper.*;
import com.evaluation.utils.Layui;
import com.evaluation.utils.MakeExcelUtil;
import com.evaluation.utils.Message;
import com.evaluation.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/pj")
public class PJController {

    @Autowired
    EvaluateEntityMapper evaluateEntityMapper;
    @Autowired
    private StudentEntityMapper studentEntityMapper;
    @Autowired
    private TeacherEntityMapper teacherEntityMapper;

    @Autowired
    private CourseEntityMapper courseEntityMapper;

    @Autowired
    private IndexTableEntityMapper indexTableEntityMapper;

    @Autowired
    private CommentMapper commentMapper;



    @RequestMapping("/getAllEva")
    public JSONObject getAllEva(@RequestParam("page") int pageNum, @RequestParam("limit") int pageSize){
        JSONObject result = new JSONObject();

        try {
            List<EvaluateEntity> list= evaluateEntityMapper.getAllEva();

            List<PJDTO> pjdtos = new ArrayList<>();

            List<Integer> ListTeaId=new ArrayList<>();
            //教师id

            for (EvaluateEntity es: list) {

                if (!ListTeaId.contains(es.getTeaId())){
                    ListTeaId.add(es.getTeaId());
                }
            }



            for (int j=0;j< ListTeaId.size();j++) {

                List<EvaluateEntity> entities=evaluateEntityMapper.getEvaAll(ListTeaId.get(j));



                List<Integer> ListCourId=new ArrayList<>();
                //该教师教了多少课程的id


                for (EvaluateEntity st: entities) {
                    //该教师教了多少课程的id
                    if (!ListCourId.contains(st.getCourseId())){
                        ListCourId.add(st.getCourseId());
                    }
                }


                for (int i=0;i< ListCourId.size();i++) {
                    List<Integer> ListStuId=new ArrayList<>();
                    //学生id

                    int counts=0;
                    //总分

                    int avgs=0;
                    //存入分数

                    String dates="";

                    //遍历课程id获取出该课程的平均分
                    PJDTO pjdto=new PJDTO();
                    for (EvaluateEntity ms: entities) {
                        if (ms.getCourseId().equals(ListCourId.get(i))){
                            //遍历该课程有多少学生并除以学生数量
                            counts=ms.getScore()+counts;
                            if (!ListStuId.contains(ms.getStuId())){
                                ListStuId.add(ms.getStuId());

                            }
                            int s= ListStuId.size();
                            avgs=counts/s;


                        }
                        dates= ms.getCreateDate();


                    }
                    SimpleDateFormat sdfs=new SimpleDateFormat("yyyy-MM-dd");

                    String dstr=dates;

                    Date date3=sdfs.parse(dstr);

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

                    TeacherEntity teacherEntity = teacherEntityMapper.getTeaName(ListTeaId.get(j));
                    CourseEntity courseEntity = courseEntityMapper.getCourseName(ListCourId.get(i));
                    pjdto.setShijian(sdf.format(date3));
                    pjdto.setCourseName(courseEntity.getCourseName());
                    pjdto.setZongfen(avgs);
                    pjdto.setTeacherName(teacherEntity.getTeaRealname());
                    pjdtos.add(pjdto);

                }

            }
            PageHelper.startPage(pageNum, pageSize);
            PageInfo<CommentEntity> pageInfo = new PageInfo(pjdtos);

            result.put("code", "0");
            result.put("msg", "操作成功！");
            result.put("data", pageInfo.getList());
            result.put("count", pageInfo.getTotal());

        }catch (Exception e){
            result.put("code", "500");
            result.put("msg", "查询异常！");

        }
        return result;

    }





    @RequestMapping("/liuyan")
    public JSONObject getGoodsList(HttpServletRequest request,@RequestParam("page") int pageNum, @RequestParam("limit") int pageSize) {
        HttpSession session = request.getSession();
        String userId = session.getAttribute("loginUserId").toString();
        Integer cstuid = Integer.parseInt(userId);
        JSONObject result = new JSONObject();
        try {
            PageHelper.startPage(pageNum, pageSize);
            PageInfo<CommentEntity> pageInfo = new PageInfo(commentMapper.getReply(cstuid));

            result.put("code", "0");
            result.put("msg", "操作成功！");
            result.put("data", pageInfo.getList());
            result.put("count", pageInfo.getTotal());
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "查询异常！");
        }
        return result;
    }



    @RequestMapping("/getReplyList")
    public JSONObject getReplyList(HttpServletRequest request,@RequestParam("page") int pageNum, @RequestParam("limit") int pageSize) {
        HttpSession session = request.getSession();
        String userId = session.getAttribute("loginUserId").toString();
        // String cstuids = session.getAttribute("loginUserId").toString();
        Integer rtid = Integer.parseInt(userId);
        JSONObject result = new JSONObject();
        try {
            PageHelper.startPage(pageNum, pageSize);
            PageInfo<CommentEntity> pageInfo = new PageInfo(commentMapper.getLiuYan(rtid));

            result.put("code", "0");
            result.put("msg", "操作成功！");
            result.put("data", pageInfo.getList());
            result.put("count", pageInfo.getTotal());
        } catch (Exception e) {
            result.put("code", "500");
            result.put("msg", "查询异常！");
        }
        return result;
    }



    @RequestMapping("/getAllTeacher")
    public Layui getAllTeacher(){
        List<TeacherEntity> teacherEntityList=teacherEntityMapper.getAllTeacher();


        return Layui.data(teacherEntityList.size(),teacherEntityList);

    }

    @RequestMapping("/getStuId")
    public Layui getStuId(){
        List<StudentEntity> studentEntities= studentEntityMapper.getStuId();

        return Layui.data(studentEntities.size(),studentEntities);
    }



    @ResponseBody
    @RequestMapping("/addreply")
    public Message addreply(@RequestBody ReplyVO replyVO){
        if (commentMapper.addReply(replyVO)>0){
            return Message.success("留言成功");
        }
        return Message.error("留言失败");


    }


    @ResponseBody
    @RequestMapping("/addCom")
    public Message addCom(@RequestBody CommentEntity commentEntity){
        if (commentMapper.addCom(commentEntity)>0){
            return Message.success("留言成功");
        }
        return Message.error("留言失败");


    }





    @RequestMapping("/Excel")
    public Message Excel(HttpServletRequest request){
        HttpSession session = request.getSession();
        String userId = session.getAttribute("loginUserId").toString();
        Integer teaId = Integer.parseInt(userId);


        try {

            List<PJDTO> pjdtos=new ArrayList<>();

            List<EvaluateEntity> entities=evaluateEntityMapper.getEvaAll(teaId);

            List<Integer> ListCourId=new ArrayList<>();
            //该教师教了多少课程的id

            for (EvaluateEntity st: entities) {
                //该教师教了多少课程的id
                if (!ListCourId.contains(st.getCourseId())){
                    ListCourId.add(st.getCourseId());
                }
            }


            for (int i=0;i< ListCourId.size();i++) {
                List<Integer> ListStuId=new ArrayList<>();
                //学生id

                int counts=0;
                //总分

                int avgs=0;
                //存入分数

                String dates="";

                //遍历课程id获取出该课程的平均分
                PJDTO pjdto=new PJDTO();
                for (EvaluateEntity ms: entities) {
                    if (ms.getCourseId().equals(ListCourId.get(i))){
                        //遍历该课程有多少学生并除以学生数量
                        counts=ms.getScore()+counts;
                        if (!ListStuId.contains(ms.getStuId())){
                            ListStuId.add(ms.getStuId());

                        }
                        int s= ListStuId.size();
                        avgs=counts/s;


                    }
                    dates= ms.getCreateDate();


                }
                SimpleDateFormat sdfs=new SimpleDateFormat("yyyy-MM-dd");

                String dstr=dates;

                Date date3=sdfs.parse(dstr);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

                TeacherEntity teacherEntity = teacherEntityMapper.getTeaName(teaId);
                CourseEntity courseEntity = courseEntityMapper.getCourseName(ListCourId.get(i));
                pjdto.setShijian(sdf.format(date3));
                pjdto.setCourseName(courseEntity.getCourseName());
                pjdto.setZongfen(avgs);
                pjdto.setTeacherName(teacherEntity.getTeaRealname());
                pjdtos.add(pjdto);

            }

            MakeExcelUtil.createExcel(pjdtos);
            return Message.success("导出成功");
        }catch (Exception e){
            return Message.success("导出失败");
        }




    }


  /*  @RequestMapping("/Excel")
    public Message Excel(HttpServletRequest request){
        HttpSession session = request.getSession();
        String userId = session.getAttribute("loginUserId").toString();
        Integer teaId = Integer.parseInt(userId);
        List<EvaluateEntity> entities=evaluateEntityMapper.getEvaAll(teaId);
        List<PJDTO> pjdtos = new ArrayList<>();


        entities.forEach(o -> {
            PJDTO pjdto = new PJDTO();
          //  Integer s=o.getTeaId();
        //    System.out.println("---------"+s+"-------------");
            pjdto.setId(o.getId());
            TeacherEntity teacherEntity = teacherEntityMapper.getTeaName(o.getTeaId());
            CourseEntity courseEntity = courseEntityMapper.getCourseName(o.getCourseId());
            IndexTableEntity indexTableEntity = indexTableEntityMapper.getIndexName(o.getEvId());
            pjdto.setTeacherName(teacherEntity.getTeaRealname());
            pjdto.setCourseName(courseEntity.getCourseName());
            pjdto.setEvName(indexTableEntity.getIndexname());
            pjdto.setShijian(o.getCreateDate());
            pjdto.setZongfen(o.getScore());
            pjdtos.add(pjdto);
        });


        try {
          MakeExcelUtil.createExcel(pjdtos);
            return Message.success("导出成功");
        }catch (Exception e){
            return Message.success("导出失败");
        }

    }*/






    /**
     * 评分列表
     * @param datas
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/add")
    public Message insert(@RequestParam(name = "datas") String datas, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userId = session.getAttribute("loginUserId").toString();
        List<EvaluateEntity> evaluateEntities = JSON.parseArray(datas, EvaluateEntity.class);
        for(EvaluateEntity eva:evaluateEntities){
            eva.setStuId(Integer.parseInt(userId));
            eva.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }
        if(evaluateEntityMapper.insertBatch(evaluateEntities)<=0){
            return Message.error("评分失败,请联系管理员");
        }
        return Message.success("评分成功");
    }

    /**
     * 评价管理
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/listLayui")
    public Layui listLayui(@RequestParam(value = "page") Integer page,
                           @RequestParam(value = "limit") Integer limit,@RequestParam(value = "teacherName",defaultValue = "")String teacherName
    ,@RequestParam(value = "studentName",defaultValue = "")String studentName) {
        EvaluateEntityExample entityExample = new EvaluateEntityExample();
        if(!"".equals(teacherName)){
            TeacherEntityExample teacherEntityExample = new TeacherEntityExample();
            teacherEntityExample.or().andTeaRealnameEqualTo(teacherName);
            TeacherEntity teacherEntity = teacherEntityMapper.selectOneByExample(teacherEntityExample);
            if(teacherEntity!=null){
                Integer teacherId=teacherEntity.getTeaId();
                entityExample.or().andTeaIdEqualTo(teacherId);
            }
        }
        if(!"".equals(studentName)){
            StudentEntityExample studentEntityExample = new StudentEntityExample();
            studentEntityExample.or().andStuRealnameEqualTo(studentName);
            StudentEntity studentEntity = studentEntityMapper.selectOneByExample(studentEntityExample);
            if(studentEntity!=null){
                Integer stuId = studentEntity.getStuId();
                entityExample.or().andStuIdEqualTo(stuId);
            }
        }
        Long count = evaluateEntityMapper.countByExample(entityExample);
        if(page!=1){
            page=(page-1)*10;
        }else{
            page=page-1;
        }
        List<EvaluateEntity> entities = evaluateEntityMapper.selectByExamplePaging(entityExample, page, limit);
        List<PJDTO> pjdtoList = new ArrayList<>();
        entities.forEach(o -> {
            PJDTO pjdto = new PJDTO();
            pjdto.setId(o.getId());
            TeacherEntity teacherEntity = teacherEntityMapper.selectByPrimaryKey(o.getTeaId());
            StudentEntity studentEntity = studentEntityMapper.selectByPrimaryKey(o.getStuId());
            CourseEntity courseEntity = courseEntityMapper.selectByPrimaryKey(o.getCourseId());
            IndexTableEntity indexTableEntity = indexTableEntityMapper.selectByPrimaryKey(o.getEvId());
            pjdto.setStudentName(studentEntity == null ? "" : studentEntity.getStuRealname());
            pjdto.setTeacherName(teacherEntity == null ? "" : teacherEntity.getTeaRealname());
            pjdto.setCourseName(courseEntity==null?"":courseEntity.getCourseName());
            pjdto.setEvName(indexTableEntity==null?"":indexTableEntity.getIndexname());
            pjdto.setShijian(o.getCreateDate());
            pjdto.setZongfen(o.getScore());
            pjdtoList.add(pjdto);
        });
        return Layui.data(count.intValue(), pjdtoList);
    }
}
